package com.dlc.shop.user.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.UserDestroyEvent;
import com.dlc.shop.bean.event.UserUnBindEvent;
import com.dlc.shop.bean.model.UserAddr;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.security.common.bo.LoginInfoBO;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.dao.AppConnectMapper;
import com.dlc.shop.security.common.enums.SocialType;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.model.AppConnect;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.service.UserAddrService;
import com.dlc.shop.user.common.model.*;
import com.dlc.shop.user.common.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author lhd
 * @date 2024/03/28 11:11
 */
@Slf4j
@Component("userUnBindListener")
@AllArgsConstructor
public class UserUnBindListener {
    private TokenStore tokenStore;

    private final AppConnectMapper appConnectMapper;

    /**
     * 用户注销时,删除相关数据
     */
    @EventListener(UserUnBindEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void userUnBindListener(UserUnBindEvent event) {
        String userId = event.getUserId();
        SysTypeEnum sysType = event.getSysType();
        if (Objects.isNull(sysType)) {
            return;
        }
        if(Objects.equals(sysType, SysTypeEnum.PLATFORM)){
            // 平台禁用解除所有社交账号的绑定
            appConnectMapper.unBindUserByUserId(userId);
        }else {
            // 只有微信公众号和小程序的登录会进行登录并绑定的操作
            LoginInfoBO loginInfoBO = tokenStore.getLoginInfoByCache();
            if(Objects.isNull(loginInfoBO)){
                return;
            }
            if (Objects.equals(loginInfoBO.getSocialType(), SocialType.MA.value()) || Objects.equals(loginInfoBO.getSocialType(), SocialType.MP.value())) {
                // 解除社交账号的绑定
                // 解除绑定的用户
                appConnectMapper.unBindUser(loginInfoBO.getBizUserId(), loginInfoBO.getSocialType());
            }
        }

    }
}
